package com.my.ruyi.ssl;

import java.nio.charset.Charset;

import javax.net.ssl.SSLEngine;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

public class SslServerInitializer extends ChannelInitializer<SocketChannel> {

	private final SslContext sslContext;
	
	public SslServerInitializer(SslContext sslContext) {
		this.sslContext = sslContext;
	}
	
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		System.out.println("SslServerInitializer-initChannel");
		ChannelPipeline pipeline = ch.pipeline();
		// 1. 使用生成用于测试目的的临时自签名证书。
		// pipeline.addLast(sslCtx.newHandler(ch.alloc()));
		
		// 2. 使用ssl证书的方式
		SSLEngine engine = sslContext.newEngine(ch.alloc());
		// 设置为服务器端模式
		engine.setUseClientMode(false);
		//不需要验证客户端
		//engine.setNeedClientAuth(false); 
		
		pipeline.addFirst("ssl", new SslHandler(engine));
		
		// On top of the SSL handler, add the text line codec.
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder(Charset.forName("UTF-8")));
        pipeline.addLast(new StringEncoder(Charset.forName("UTF-8")));
        
        // 添加自己的业务处理逻辑
        pipeline.addLast(new SslServerHandler());
        
	}

}
